﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.Skins;
using DevExpress.LookAndFeel;
using DevExpress.UserSkins;
using DevExpress.XtraBars;
using DevExpress.XtraBars.Ribbon;
using DevExpress.XtraBars.Helpers;
using CNotebook;
using CNotebook.Sales;

namespace NotebookS2
{
    public partial class ARCreditMemo : RibbonForm
    {
        public ARCreditMemo()
        {
            InitializeComponent();
        }

        public int ObjectType
        {
            get { return 10; }
        }
        public string ConnectionString { get; set; }
        public string ActiveUserID { get; set; }

        public DataTable LineItems { get; set; }

        public void PrintPreview()
        {
            PRNT_ARCM oPrint = new PRNT_ARCM();

            oPrint.ConnectionString = this.ConnectionString;
            oPrint.DocumentNumber = txtDocNum.Text;

            oPrint.WindowState = FormWindowState.Maximized;
            oPrint.ShowDialog();
        }

        int FullAccess()
        {
            txtStatus.Properties.Buttons[0].Enabled = true;
            txtStatus.Properties.Buttons[1].Enabled = true;
            
            return 1;
        }

        int ApplyReadOnly()
        {
            DisableControls();

            txtStatus.Properties.Buttons[0].Enabled = false;
            txtStatus.Properties.Buttons[1].Enabled = false;
            
            return 2;
        }

        int  NoAccess()
        {
            MessageBox.Show("You have no right to access this module!!!!", "Security Policy", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            return 3;
        }
        string ApplyAuthorization()
        {
            UserManager oManager = new UserManager();

            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();

            string iAccessType = oManager.GetAccessType(this.ObjectType, this.ActiveUserID);

            oManager.Close();

            switch (iAccessType)
            {
                case "Full Access":
                    FullAccess();
                    break;
                case "Read Only":
                    ApplyReadOnly();
                    break;
                case "No Access":
                    NoAccess();
                    break;
            }

            return iAccessType;
        }
        public void ShowSearch()
        {
            FND_ARCM oForm = new FND_ARCM();

            oForm.ConnectionString = this.ConnectionString;
            oForm.ShowDialog();

            string _DOC_NUMBER = oForm.SelectedDocumentNumber;

            CreditMemoManager oManager = new CreditMemoManager();

            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();

            DataTable dt = new DataTable();

            dt = oManager.GetCreditMemo(_DOC_NUMBER);
            DataRow oRow = dt.Rows[0];

            txtDocNum.Text = _DOC_NUMBER;

            txtCardCode.Text = oRow["CardCode"].ToString();
            txtCardName.Text = oRow["CardName"].ToString();

            txtRemarks.Text = oRow["Remarks"].ToString();
            txtStatus.Text = oRow["DocStatus"].ToString();

            txtCreatedBy.Text = oRow["CreatedBy"].ToString();
            dtDateCreated.EditValue = Convert.ToDateTime(oRow["DateCreated"].ToString());
            txtModifiedBy.Text = oRow["ModifiedBy"].ToString();
            dtDateModified.EditValue = Convert.ToDateTime(oRow["DateModified"].ToString());
            txtTotalAmount.Text = oRow["TotalAmount"].ToString();

            this.LineItems = oManager.GetCreditMemoLineItems(_DOC_NUMBER);

            grdCntrlCreditMemo.DataSource = this.LineItems;
            grdCntrlCreditMemo.Refresh();

            ComputeTotal();

            oManager.Close();

            btnAdd.Text = "Update";

            if (txtStatus.Text == "Draft")
            {
                if (grdViewCreditMemo.RowCount == 0)
                {
                    grdViewCreditMemo.AddNewRow();
                }
            }

        }

        void InitializeSeries()
        {

            string _SERIES_CODE = "10";
            SeriesManager oSeries = new SeriesManager();
            oSeries.ConnectionString = this.ConnectionString;
            oSeries.Open();

            if (oSeries.IsAutoNumber(_SERIES_CODE) == true)
            {
                txtDocNum.Properties.ReadOnly = true;
                txtDocNum.Text = "##########";

            }
            oSeries.Close();

        }
        

        void DisableControls()
        {
            txtRemarks.Enabled = false;
            txtCardCode.Enabled = false;
            txtCardName.Enabled = false;
            btnAdd.Enabled = false;
            grdViewCreditMemo.OptionsBehavior.Editable = false;
        }

        void EnableControls()
        {

            txtRemarks.Enabled = true;
            txtCardCode.Enabled = true;
            txtCardName.Enabled = true;
            btnAdd.Enabled = true;
            grdViewCreditMemo.OptionsBehavior.Editable = true;


        }

        void ComputeTotal()
        {
            double _Total = 0;

            foreach (DataRow oRow in this.LineItems.Rows)
            {
                if (oRow["Amount"] != DBNull.Value)
                {
                    _Total = _Total + Convert.ToDouble(oRow["Amount"]);
                }
            }

            txtTotalAmount.Text = _Total.ToString("#,###.00");
        }

        void RemoveBlankLastRowFirst()
        {
            try
            {
                int iCount = -1;
                grdViewCreditMemo.MoveLast();

                int[] oRow = grdViewCreditMemo.GetSelectedRows();

                iCount = oRow[0];
                string sItemCode = "";


                sItemCode = grdViewCreditMemo.GetRowCellValue(iCount, grdViewCreditMemo.Columns["AcctCode"]).ToString();

                if (sItemCode.Trim() == "")
                {
                    grdViewCreditMemo.DeleteRow(iCount);
                }
            }
            catch
            {
            }

        }

        public void InitializeTable()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("AcctCode", typeof(string));
            dt.Columns.Add("AcctName", typeof(string));
            dt.Columns.Add("RefNo", typeof(string));
            dt.Columns.Add("Particulars", typeof(string));
            dt.Columns.Add("Amount", typeof(double));

            this.LineItems = dt;

        }

        string GetNewSeries()
        {
            string _SERIES = "";
            string _DOCTYPE = "10";

            SeriesManager oSeries = new SeriesManager();
            oSeries.ConnectionString = this.ConnectionString;
            oSeries.Open();
            if (oSeries.IsAutoNumber(_DOCTYPE) == true)
            {
                _SERIES = oSeries.GetNewSeries(_DOCTYPE);
            }
            else
            {
                _SERIES = txtDocNum.Text;
            }
            oSeries.Close();

            return _SERIES;
        }


        private void ARCreditMemo_Load(object sender, EventArgs e)
        {

            InitializeSeries();

            dtPostDate.EditValue = System.DateTime.Now;

            txtCreatedBy.Text = this.ActiveUserID;
            dtDateCreated.EditValue = System.DateTime.Now;
            txtModifiedBy.Text = this.ActiveUserID;
            dtDateModified.EditValue = System.DateTime.Now;

            InitializeTable();

            grdCntrlCreditMemo.DataSource = this.LineItems;
            grdCntrlCreditMemo.Refresh();


            if (grdViewCreditMemo.RowCount <= 0)
            {
                grdViewCreditMemo.AddNewRow();
            }

        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            RemoveBlankLastRowFirst();
            
            CreditMemoManager oManager = new CreditMemoManager();
            CreditMemoUnit oUnit = new CreditMemoUnit();

            if (btnAdd.Text == "Add")
            {
                txtDocNum.Text = GetNewSeries();

                oUnit.DocNum = txtDocNum.Text;
                oUnit.CardCode = txtCardCode.Text;
                oUnit.CardName = txtCardName.Text;
                oUnit.DocStatus = txtStatus.Text;
                oUnit.Remarks = txtRemarks.Text;
                oUnit.TotalAmount = Convert.ToDouble(txtTotalAmount.Text);

                oUnit.DocDate = Convert.ToDateTime(dtPostDate.EditValue);

                oUnit.DateCreated = Convert.ToDateTime(dtDateCreated.EditValue);
                oUnit.CreatedBy = txtCreatedBy.Text;
                oUnit.DateModified = Convert.ToDateTime(dtDateModified.EditValue);
                oUnit.ModifiedBy = txtModifiedBy.Text;

                oUnit.LineItems = this.LineItems;


                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                oManager.AddCreditMemo(oUnit);
                oManager.Close();

                MessageBox.Show("Document saved!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);

                btnAdd.Text = "Update";

                if (txtStatus.Text == "Draft")
                {
                    if (grdViewCreditMemo.RowCount == 0)
                    {
                        grdViewCreditMemo.AddNewRow();
                    }
                }
            }
            else
            {

                oUnit.DocNum = txtDocNum.Text;
                oUnit.CardCode = txtCardCode.Text;
                oUnit.CardName = txtCardName.Text;
                oUnit.DocStatus = txtStatus.Text;
                oUnit.Remarks = txtRemarks.Text;
                oUnit.TotalAmount = Convert.ToDouble(txtTotalAmount.Text);

                oUnit.DocDate = Convert.ToDateTime(dtPostDate.EditValue);

                oUnit.DateCreated = Convert.ToDateTime(dtDateCreated.EditValue);
                oUnit.CreatedBy = txtCreatedBy.Text;
                oUnit.DateModified = Convert.ToDateTime(dtDateModified.EditValue);
                oUnit.ModifiedBy = txtModifiedBy.Text;

                oUnit.LineItems = this.LineItems;


                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();

                oManager.UpdateCreditMemo(oUnit);
                oManager.Close();

                MessageBox.Show("Document saved!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                if (txtStatus.Text == "Draft")
                {
                    if (grdViewCreditMemo.RowCount == 0)
                    {
                        grdViewCreditMemo.AddNewRow();
                    }
                }
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

         void CancelDocument()
        {
            if (MessageBox.Show("Are you sure you want to Cancel this Document?", "Post Document", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                CreditMemoManager oManager = new CreditMemoManager();

                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();


                oManager.CancelDocument(txtDocNum.Text);

                oManager.Close();
            }

        }

        void PostDocument()
        {
            if (MessageBox.Show("Are you sure you want to post this Document?", "Cancel Document", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                CreditMemoManager oManager = new CreditMemoManager();

                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();


                oManager.PostDocument(txtDocNum.Text);
                txtStatus.Text = "Posted";
                oManager.Close();
            }

        }

        void CloseDocument()
        {
            if (MessageBox.Show("Are you sure you want to post this Document?", "Cancel Document", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                CreditMemoManager oManager = new CreditMemoManager();

                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();


                oManager.CloseDocument(txtDocNum.Text);
                txtStatus.Text = "Closed";
                oManager.Close();
            }

        }

        private void grdViewCreditMemo_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Down)
            {
                if (grdViewCreditMemo.IsLastRow)
                {

                    string sItemCode = "";

                    int iCount = grdViewCreditMemo.FocusedRowHandle;
                    sItemCode = grdViewCreditMemo.GetRowCellValue(iCount, grdViewCreditMemo.Columns["AcctCode"]).ToString();

                    if (sItemCode != "" && (txtStatus.Text == "Draft"))
                    {
                        grdViewCreditMemo.AddNewRow();

                        grdCntrlCreditMemo.Select();
                        grdViewCreditMemo.FocusedRowHandle = DevExpress.XtraGrid.GridControl.NewItemRowHandle;
                        grdViewCreditMemo.FocusedColumn = grdViewCreditMemo.VisibleColumns[1];
                        grdViewCreditMemo.ShowEditor();


                    }
                }
            }
        }

        private void txtAcctCode_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            FND_GLACCOUNT oForm = new FND_GLACCOUNT();

            oForm.ConnectionString = this.ConnectionString;

            oForm.ShowDialog();

            grdViewCreditMemo.SetRowCellValue(grdViewCreditMemo.FocusedRowHandle, grdViewCreditMemo.Columns["AcctCode"], oForm.SelectedGLAcctCode);
            grdViewCreditMemo.SetRowCellValue(grdViewCreditMemo.FocusedRowHandle, grdViewCreditMemo.Columns["AcctName"], oForm.SelectedGLAcctName);


        }

        private void txtStatus_EditValueChanged(object sender, EventArgs e)
        {
            if (txtStatus.Text == "Posted")
            {
                DisableControls();
                txtStatus.Properties.Buttons[0].Visible = false;
                txtStatus.Properties.Buttons[1].Visible = true;
            }

            if (txtStatus.Text == "Draft")
            {
                EnableControls();
                txtStatus.Properties.Buttons[0].Visible = true;
                txtStatus.Properties.Buttons[1].Visible = true;
            }

            if (txtStatus.Text == "Canceled")
            {
                DisableControls();
                txtStatus.Properties.Buttons[0].Visible = false;
                txtStatus.Properties.Buttons[1].Visible = false;
            }

            if (txtStatus.Text == "Closed")
            {
                DisableControls();
                txtStatus.Properties.Buttons[0].Visible = false;
                txtStatus.Properties.Buttons[1].Visible = false;
            }
        }

        private void txtStatus_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {

            switch (e.Button.Index)
            {
                case 0:
                    // Post

                    PostDocument();
                    
                    break;
                case 1:
                    // Cancel:
                    if (txtStatus.Text == "Draft")
                    {
                        CancelDocument();
                    }
                    else if (txtStatus.Text == "Posted")
                    {
                        CloseDocument();
                    }
                    break;
            }
        }

        private void txtAcctCode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                DevExpress.XtraEditors.TextEdit _TEXT_ACCOUNTCODE = (DevExpress.XtraEditors.TextEdit)sender;

                ChartOfAccountManager oManager = new ChartOfAccountManager();

                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                DataTable dt = oManager.GetChartOfAccountByAcctCode(_TEXT_ACCOUNTCODE.Text);
                oManager.Close();


                if (dt.Rows.Count > 0)
                {
                    DataRow oRow = dt.Rows[0];

                    string sAcctCode = oRow["AcctCode"].ToString();
                    string sAcctName = oRow["AcctName"].ToString();
                    grdViewCreditMemo.SetRowCellValue(grdViewCreditMemo.FocusedRowHandle, grdViewCreditMemo.Columns["AcctCode"], sAcctCode);
                    grdViewCreditMemo.SetRowCellValue(grdViewCreditMemo.FocusedRowHandle, grdViewCreditMemo.Columns["AcctName"], sAcctName);


                }

                else
                {

                    FND_GLACCOUNT oForm = new FND_GLACCOUNT();

                    DevExpress.XtraEditors.TextEdit eGLAccount = (DevExpress.XtraEditors.TextEdit)sender;

                    oForm.ConnectionString = this.ConnectionString;
                    oForm.SetSearch(eGLAccount.Text);
                    oForm.ShowDialog();

                    grdViewCreditMemo.SetRowCellValue(grdViewCreditMemo.FocusedRowHandle, grdViewCreditMemo.Columns["AcctCode"], oForm.SelectedGLAcctCode);
                    grdViewCreditMemo.SetRowCellValue(grdViewCreditMemo.FocusedRowHandle, grdViewCreditMemo.Columns["AcctName"], oForm.SelectedGLAcctName);

                }
                //grdViewCreditMemo.FocusedColumn = grdViewCreditMemo.Columns["Particulars"];

            }
        }

        private void txtAmount_KeyDown(object sender, KeyEventArgs e)
        {

            if (e.KeyCode == Keys.Down)
            {
                DevExpress.XtraEditors.TextEdit _TEXT_AMOUNT = (DevExpress.XtraEditors.TextEdit)sender;

                grdViewCreditMemo.SetRowCellValue(grdViewCreditMemo.FocusedRowHandle, grdViewCreditMemo.Columns["Amount"], _TEXT_AMOUNT.Text);
                grdViewCreditMemo.FocusedColumn = grdViewCreditMemo.Columns["AcctCode"];
                grdViewCreditMemo.ShowEditor();

                ComputeTotal();
            }

            if (e.KeyCode == Keys.Enter)
            {
                DevExpress.XtraEditors.TextEdit _TEXT_AMOUNT = (DevExpress.XtraEditors.TextEdit)sender;

                grdViewCreditMemo.SetRowCellValue(grdViewCreditMemo.FocusedRowHandle, grdViewCreditMemo.Columns["Amount"], _TEXT_AMOUNT.Text);
                grdViewCreditMemo.FocusedColumn = grdViewCreditMemo.Columns["AcctCode"];
                grdViewCreditMemo.ShowEditor();

                SendKeys.Send("{DOWN}");

                ComputeTotal();
            }

            if (e.KeyCode == Keys.Tab)
            {
                DevExpress.XtraEditors.TextEdit _TEXT_AMOUNT = (DevExpress.XtraEditors.TextEdit)sender;

                grdViewCreditMemo.SetRowCellValue(grdViewCreditMemo.FocusedRowHandle, grdViewCreditMemo.Columns["Amount"], _TEXT_AMOUNT.Text);
                grdViewCreditMemo.FocusedColumn = grdViewCreditMemo.Columns["AcctCode"];
                grdViewCreditMemo.ShowEditor();

                SendKeys.Send("{DOWN}");

                ComputeTotal();
            }
        }

        private void grdViewCreditMemo_KeyDown_1(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                if (MessageBox.Show("Are you sure you want to delete this row?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == System.Windows.Forms.DialogResult.Yes)
                {
                    grdViewCreditMemo.DeleteRow(grdViewCreditMemo.FocusedRowHandle);
                }
            }

            if (e.KeyCode == Keys.Down)
            {
                
                if (grdViewCreditMemo.IsLastRow)
                {

                    string sItemCode = "";

                    int iCount = grdViewCreditMemo.FocusedRowHandle;
                    sItemCode = grdViewCreditMemo.GetRowCellValue(iCount, grdViewCreditMemo.Columns["AcctCode"]).ToString();

                    if (sItemCode != "" && (txtStatus.Text == "Draft"))
                    {
                        grdViewCreditMemo.AddNewRow();

                        grdCntrlCreditMemo.Select();
                        grdViewCreditMemo.FocusedRowHandle = DevExpress.XtraGrid.GridControl.NewItemRowHandle;
                        grdViewCreditMemo.FocusedColumn = grdViewCreditMemo.Columns["AcctCode"];
                        grdViewCreditMemo.ShowEditor();


                    }
                }
            }

        }

        private void txtCardCode_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            FND_BP _SearchBP = new FND_BP();

            AddressBookManager oBPManager = new AddressBookManager();
            TaxManager oTxManager = new TaxManager();

            try
            {


                _SearchBP.ConnectionString = this.ConnectionString;
                _SearchBP.BusinessPartnerType = "Customer";
                _SearchBP.ShowDialog();

                txtCardCode.Text = _SearchBP.CardCode;
                txtCardName.Text = _SearchBP.CardName;
            }
            catch
            {
            }
        }

        private void ribbonControl1_Click(object sender, EventArgs e)
        {

        }

        private void grdViewCreditMemo_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
        {
            ComputeTotal();
        }

        private void txtRefNo_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            FND_INVOICE oForm = new FND_INVOICE();

            oForm.ConnectionString = this.ConnectionString;
            oForm.ShowDialog();

            if (oForm.DocumentNumber != null)
            {
                grdViewCreditMemo.SetRowCellValue(grdViewCreditMemo.FocusedRowHandle, grdViewCreditMemo.Columns["RefNo"], oForm.DocumentNumber);
            }
        }

        private void ARCreditMemo_Shown(object sender, EventArgs e)
        {
            string _USR_AUTHORIZATION = ApplyAuthorization();
            if (_USR_AUTHORIZATION == "No Access")
            {
                btnCancel_Click(sender, e);
            }
        }

     }
    }
